#encoding: utf-8 
require 'rubygems'
require 'nokogiri'
require 'open-uri'
require 'ostruct'
require 'json'
require 'iconv'

namespace :epg do
  namespace :guide do
    task :check => :environment do
      if File.exist?("#{Rails.root.to_s}/public/guides/#{Time.now.stamp('2013-02-28')}.json") and !ENV['force']
        puts "guides has been loaded"
      else
        load_guides
      end
    end

    def load_guides
      url1 = 'http://epg.tvsou.com/programws/TV_24/Channel_46/W4.htm'
      url2 = 'http://epg.tvsou.com/program/TV_21/Channel_43/W3.htm'
      url3 = 'http://epg.tvsou.com/program/TV_64/Channel_226/W3.htm'
      url4 = 'http://epg.tvsou.com/programys/TV_1/Channel_1/W2.htm'
      epg = {}
      [url4, url1, url3, url2].each do |url|
        epg.merge! load_epg_from_tvsou(url)
      end

      File.open("#{Rails.root.to_s}/public/guides/#{Time.now.stamp("2013-02-28")}.json","w") do |f|
        f.write(epg.to_json)
      end
    end

    def load_epg_from_tvsou url
      televisions = Hash.new
      begin
        page = Nokogiri::HTML(open(url), nil, 'gbk')
        #page.encoding = "gbk"

        #name = to_utf8(page.at('#epg_m1').at('b').content).split('|').first
        name = to_utf8 page.css(".listmenu2").first.at('font').content.strip
        if tv = Television.where(:name => name).first
          #puts name 
          televisions[tv.id.to_s] = load_guide(page)
          puts "load #{televisions[tv.id.to_s].count} guides for #{tv.name}"
        end
      
        page.css(".listmenu2").first.css("a").each do |link|
          begin
            #if tv = Television.where(:name => to_utf8(subpage.at('#epg_m1').at('b').content.strip)).first
            if tv = Television.where(:name => link.content).first
              #puts "load guide for #{link.content.strip}"
              subpage = Nokogiri::HTML(open('http://epg.tvsou.com'+link[:href]), nil, 'gbk')
              televisions[tv.id.to_s] = load_guide(subpage)
              puts "load #{televisions[tv.id.to_s].count} guides for #{tv.name}"
            end
          rescue Exception => e
            puts e.inspect 
          end
        end    
      rescue Exception => e
        pp e.inspect 
      end
      televisions
    end

    def to_utf8 text
      converter = Iconv.new 'UTF-8//IGNORE', 'UTF-8'
      converter.iconv(text).strip
    end

    def load_guide page
      guides = Array.new
      (page.css('#PMT1')+page.css('#PMT2')).each do |item|
        if item.at('a.black') and item.at('font')
          guide = Hash.new
          guide[:name] = item.at('a.black').content
          guide[:start] = Time.now.strftime("%Y-%m-%d ")+ item.at('font').content.strip + ":00"
          guides << guide
        end
      end
      guides.sort! {|x, y| y[:start] <=> x[:start]} 
    end

    def load_epg_from_wasu televisions = Hash.new
      Nokogiri::HTML(open('http://live.wasu.cn/liveplay/id/438')).css(".sidebarIcon .payingiteninfo a").each do |link|
        begin
          if tv = Television.where(:name => link.content).first
            page = Nokogiri::HTML(open('http://live.wasu.cn'+link[:href]))
            guides = Array.new
            page.css('.playing li').each do |item|
              guide = Hash.new
              if item.at('em') and item.at('span')
                guide[:name] = item.at('span').content
                guide[:start] = item.at('em').content
                guides << guide
              end
            end
            guides.sort! {|x, y| y[:start] <=> x[:start]} 
            televisions[tv.id.to_s] = guides
          end
        rescue Exception => e
          pp e.inspect 
        end
      end
      televisions
    end
  end
end